package cn.iocoder.yudao.module.member.service.praxisProjectResult;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.member.controller.admin.praxisProjectResult.vo.*;
import cn.iocoder.yudao.module.member.convert.praxisProjectResult.PraxisProjectResultConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.praxisAnnex.PraxisAnnexDO;
import cn.iocoder.yudao.module.member.dal.dataobject.praxisProject.PraxisProjectDO;
import cn.iocoder.yudao.module.member.dal.dataobject.praxisProjectResult.PraxisProjectResultDO;
import cn.iocoder.yudao.module.member.dal.mysql.praxisAnnex.PraxisAnnexMapper;
import cn.iocoder.yudao.module.member.dal.mysql.praxisProject.PraxisProjectMapper;
import cn.iocoder.yudao.module.member.dal.mysql.praxisProjectResult.PraxisProjectResultMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.PRAXIS_PROJECT_RESULT_EXISTS;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.PRAXIS_PROJECT_RESULT_NOT_EXISTS;

/**
 * 项目结果公示 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class PraxisProjectResultServiceImpl implements PraxisProjectResultService {

    @Resource
    private PraxisProjectResultMapper praxisProjectResultMapper;
    @Resource
    private PraxisProjectMapper praxisProjectMapper;
    @Resource
    private PraxisAnnexMapper annexMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPraxisProjectResult(PraxisProjectResultCreateReqVO createReqVO) {
        // 插入
        Long aLong = praxisProjectResultMapper.selectCount(new QueryWrapper<PraxisProjectResultDO>().eq("project_id", createReqVO.getProjectId())
                .eq("deleted", 0));
        if(null!=aLong && aLong>0){
            throw exception(PRAXIS_PROJECT_RESULT_EXISTS);
        }
        PraxisProjectResultDO praxisProjectResult = PraxisProjectResultConvert.INSTANCE.convert(createReqVO);
        Date date = new Date();
        praxisProjectResult.setCreateTime(date);
        praxisProjectResult.setUpdateTime(date);
        String loginUserName = WebFrameworkUtils.getLoginUserName();
        praxisProjectResult.setCreator(loginUserName);
        praxisProjectResult.setUpdater(loginUserName);
        praxisProjectResultMapper.insert(praxisProjectResult);
        List<PraxisAnnexBaseVO> annexList = createReqVO.getAnnexList();
        if(CollectionUtils.isNotEmpty(annexList)){
            List<PraxisAnnexDO> pList=new ArrayList<>();
            annexList.stream().forEach(m->{
                PraxisAnnexDO a=new PraxisAnnexDO();
                BeanUtils.copyProperties(m,a);
                a.setId(null);
                a.setRelationId(praxisProjectResult.getId());
                a.setRelationType(2);
                a.setCreateTime(date);
                pList.add(a);
            });
            annexMapper.insertBatch(pList);
        }
        return praxisProjectResult.getId();
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePraxisProjectResult(PraxisProjectResultUpdateReqVO updateReqVO) {
        // 插入
        Long aLong = praxisProjectResultMapper.selectCount(new QueryWrapper<PraxisProjectResultDO>().eq("project_id", updateReqVO.getProjectId())
                .eq("deleted", 0).ne("id",updateReqVO.getId()));
        if(null!=aLong && aLong>0){
            throw exception(PRAXIS_PROJECT_RESULT_EXISTS);
        }
        // 校验存在
        this.validatePraxisProjectResultExists(updateReqVO.getId());
        // 更新
        PraxisProjectResultDO updateObj = PraxisProjectResultConvert.INSTANCE.convert(updateReqVO);
        updateObj.setUpdateTime(new Date());
        updateObj.setUpdater( WebFrameworkUtils.getLoginUserName());
        praxisProjectResultMapper.updateById(updateObj);
        List<PraxisAnnexBaseVO> annexList = updateReqVO.getAnnexList();
        annexMapper.delete(new QueryWrapper<PraxisAnnexDO>().eq("relation_id",updateReqVO.getId()).eq("relation_type",2));
        if(CollectionUtils.isNotEmpty(annexList)){
            List<PraxisAnnexDO> pList=new ArrayList<>();
            annexList.stream().forEach(m->{
                PraxisAnnexDO a=new PraxisAnnexDO();
                BeanUtils.copyProperties(m,a);
                a.setId(null);
                a.setRelationId(updateReqVO.getId());
                a.setCreateTime(new Date());
                a.setRelationType(2);
                pList.add(a);
            });
            annexMapper.insertBatch(pList);
        }
    }

    @Override
    public void release(@Valid PraxisProjectResultUpdateReqVO updateReqVO) {
        PraxisProjectResultDO reqVO=new PraxisProjectResultDO();
        reqVO.setId(updateReqVO.getId());
        reqVO.setReleaseTime(new Date());
        reqVO.setExamineFlag(1);
        reqVO.setStatus(2);
        reqVO.setUpdateTime(new Date());
        reqVO.setUpdater( WebFrameworkUtils.getLoginUserName());
        praxisProjectResultMapper.updateById(reqVO);
    }
    @Override
    public void deletePraxisProjectResult(Long id) {
        // 校验存在
        this.validatePraxisProjectResultExists(id);
        // 删除
        praxisProjectResultMapper.deleteById(id);
    }

    @Override
    public void examinePraxisProjectResult( PraxisProjectResultUpdateVO updateReqVO) {
        this.validatePraxisProjectResultExists(updateReqVO.getId());
        PraxisProjectResultDO reqVO=new PraxisProjectResultDO();
        reqVO.setId(updateReqVO.getId());
        Integer examineStatus = updateReqVO.getExamineStatus();
        reqVO.setExamineStatus(examineStatus);
        reqVO.setExamineNotes(updateReqVO.getExamineNotes());
        reqVO.setExamineFlag(1);
        if(examineStatus==0){
            reqVO.setStatus(0);
        }else if(examineStatus==1){
            reqVO.setReleaseTime(new Date());
            reqVO.setStatus(2);
        }
        reqVO.setUpdateTime(new Date());
        reqVO.setUpdater( WebFrameworkUtils.getLoginUserName());
        praxisProjectResultMapper.updateById(reqVO);
    }
    private void validatePraxisProjectResultExists(Long id) {
        if (praxisProjectResultMapper.selectById(id) == null) {
            throw exception(PRAXIS_PROJECT_RESULT_NOT_EXISTS);
        }
    }

    @Override
    public PraxisProjectResultRespVO getPraxisProjectResultById(Long id) {
        PraxisProjectResultDO p = praxisProjectResultMapper.selectById(id);
        if (p== null) {
            throw exception(PRAXIS_PROJECT_RESULT_NOT_EXISTS);
        }
        PraxisProjectResultRespVO r = PraxisProjectResultConvert.INSTANCE.convert(p);
        QueryWrapper<PraxisProjectDO> q=new QueryWrapper<>();
        q.select("title").eq("id",p.getProjectId()).last("limit 1");
        PraxisProjectDO projectDO = praxisProjectMapper.selectOne(q);
        if(projectDO!=null){
            r.setProjectName(projectDO.getTitle());
        }
        if(null!=r){
            QueryWrapper<PraxisAnnexDO> queryWrapper = new QueryWrapper<PraxisAnnexDO>()
                    .select("id, annex_name, annex_url, relation_id, relation_type, creator, create_time")
                    .eq("relation_id", id).eq("relation_type", 2);
            List<PraxisAnnexDO> annexDOList = annexMapper.selectList(queryWrapper);
            if(CollectionUtils.isNotEmpty(annexDOList)){
                List<PraxisAnnexBaseVO> pList=new ArrayList<>();
                annexDOList.stream().forEach(m->{
                    PraxisAnnexBaseVO a=new PraxisAnnexBaseVO();
                    BeanUtils.copyProperties(m,a);
                    pList.add(a);
                });
                r.setAnnexList(pList);
            }
        }
        return r;
    }

    @Override
    public PageResult<PraxisProjectResultRespVO> getProjectResultPage(PraxisProjectResultPageReqVO pageReqVO) {
        IPage<PraxisProjectResultRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getTitle())){
            params.put("title",pageReqVO.getTitle());
        }
        if(null!=pageReqVO.getStatus()){
            params.put("status",pageReqVO.getStatus());
        }
        mpPage.setRecords(praxisProjectResultMapper.getPraxisProjectResultPage(mpPage, params));
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public PageResult<PraxisProjectResultRespVO> getPraxisProjectResultPage(PraxisProjectResultPageReqVO pageReqVO) {
        // MyBatis Plus 查询
        IPage<PraxisProjectResultRespVO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(pageReqVO.getTitle())){
            params.put("title",pageReqVO.getTitle());
        }
        if(StringUtils.isNotBlank(pageReqVO.getCompanyName())){
            params.put("companyName",pageReqVO.getCompanyName());
        }
        if(StringUtils.isNotBlank(pageReqVO.getCreator())){
            params.put("creator",pageReqVO.getCreator());
        }
        if(StringUtils.isNotBlank(pageReqVO.getDept())){
            params.put("dept",pageReqVO.getDept());
        }
        if(null!=pageReqVO.getStatus()){
            params.put("status",pageReqVO.getStatus());
        }
        mpPage.setRecords(praxisProjectResultMapper.getPraxisProjectResultPage(mpPage, params));
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public List<PraxisProjectResultDO> getPraxisProjectResultList(PraxisProjectResultExportReqVO exportReqVO) {
        return null;
    }

}
